using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Write.Api.Application.Command.Pharmacy;
using SmartHealthcare.Write.Api.DTo;

namespace SmartHealthcare.Write.Api.Application.Handler.Pharmacy
{
    /// <summary>
    /// 发药处理器
    /// </summary>
    public class DispenseMedicineHandler : IRequestHandler<DispenseMedicineCommand, APIResult<PharmacyOperationDto>>
    {
        private readonly IBaseRepository<Prescription> prescriptionRepository;
        private readonly ILogger<DispenseMedicineHandler> logger;

        public DispenseMedicineHandler(
            IBaseRepository<Prescription> prescriptionRepository,
            ILogger<DispenseMedicineHandler> logger)
        {
            this.prescriptionRepository = prescriptionRepository;
            this.logger = logger;
        }

        public async Task<APIResult<PharmacyOperationDto>> Handle(DispenseMedicineCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<PharmacyOperationDto>();
            
            try
            {
                // 获取处方信息
                var prescription = await prescriptionRepository.GetALL()
                    .FirstOrDefaultAsync(x => x.Id == request.PrescriptionId && x.IsDeleted == false, cancellationToken);

                if (prescription == null)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "处方不存在";
                    return result;
                }

                // 检查处方状态
                if (prescription.State != 1)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "处方状态不正确，无法发药";
                    return result;
                }

                // 更新处方状态为已发药（状态2）
                prescription.State = 2;
                
                prescriptionRepository.Update(prescription);

                var operationResult = new PharmacyOperationDto
                {
                    Success = true,
                    Message = "发药成功",
                    PrescriptionId = request.PrescriptionId
                };

                result.Data = operationResult;
                result.Code = APIEnums.Success;
                result.Msg = "发药成功";
                
                logger.LogInformation($"处方发药成功，处方ID：{request.PrescriptionId}");
            }
            catch (Exception ex)
            {
                result.Code = APIEnums.Error;
                result.Msg = "发药失败：" + ex.Message;
                logger.LogError(ex, "处方发药失败");
            }

            return result;
        }
    }
} 